package com.leetcode.studyplan.algorithm.introduction.secondday;

public class L_977_SquaresOfASortedArray {

    public int[] sortedSquares(int[] nums) {
        if (nums == null || nums.length == 0) {
            return nums;
        }

        int[] result = new int[nums.length];
        int resultPoint = 0;
        // 先找到负数和正数的临界点

        int left = 0;
        int right = 1;
        for (int i = 0; i < nums.length - 1; i++) {
            if (nums[i] < 0 && nums[i + 1] >= 0) {
                left = i;
                right = i + 1;
                break;
            }
            if (i == nums.length - 2 && nums[i] < 0) {
                left = i;
                right = i + 1;
            }
        }

        Integer leftValue = null;
        Integer rightValue = null;
        while (left >= 0 && right < nums.length) {
            leftValue = nums[left] * nums[left];
            rightValue = nums[right] * nums[right];

            if (leftValue >= rightValue) {
                result[resultPoint++] = rightValue;
                right++;
            } else {
                result[resultPoint++] = leftValue;
                left--;
            }
        }

        while (left >= 0) {
            result[resultPoint++] = nums[left] * nums[left];
            left--;
        }
        while (right < nums.length) {
            result[resultPoint++] = nums[right] * nums[right];
            right++;
        }
        return result;
    }

}
